package com.yuncool.service;

import cn.hutool.core.util.IdUtil;
import com.yuncool.ServiceResult;
import com.yuncool.constants.CommonConstants;
import com.yuncool.constants.ResultCode;
import com.yuncool.domain.MemberInfo;
import com.yuncool.domain.MemberPart;
import com.yuncool.domain.vo.RegisteredRequestVO;
import com.yuncool.mapper.MemberInfoMapper;
import com.yuncool.mapper.MemberPartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class MemberInfoService {

	@Resource
	private MemberInfoMapper memberInfoMapper;
	@Autowired
	private MemberPartMapper memberPartMapper;

	/**
	 * 注册用户
	 *
	 * @param vo
	 * @return
	 */
	@Transactional
	public ServiceResult<Boolean> registeredUser(RegisteredRequestVO vo) {
		ServiceResult<Boolean> result = new ServiceResult<>();
		/**
		 * 校验逻辑(重复校验)
		 * 1.判断手机号或邮箱是否已经注册
		 */
		MemberInfo memberInfo = memberInfoMapper.loadUserByUsername(vo.getLoginId());
		if (memberInfo != null) {
			result.setError(ResultCode.REQUEST_ERROR_EXIST_DATA, "用户已存在!");
			return result;
		}
		MemberInfo base = new MemberInfo();
		base.setIsValid(CommonConstants.DATA_ISVALID);
		base.setUserName(vo.getUsername());
		base.setUserPassword(new BCryptPasswordEncoder().encode(vo.getPassword()));
		String uid = IdUtil.simpleUUID().toUpperCase();
		base.setUserId(uid);
		if (CommonConstants.USER_REGISTERED_TYPE_PHONE.equals(vo.getRegisteredType())) {
			//手机号注册
			base.setUserPhone(vo.getLoginId());
		} else if (CommonConstants.USER_REGISTERED_TYPE_EMAIL.equals(vo.getRegisteredType())) {
			//邮箱注册
			base.setUserEmail(vo.getLoginId());
		}
		memberInfoMapper.insertSelective(base);
		//插入扩展信息
		insertMemberPart(uid, vo);
		return result;
	}

	@Async
	void insertMemberPart(String uid, RegisteredRequestVO vo) {
		MemberPart memberPart = new MemberPart();
		memberPart.setMemberId(uid);
		memberPart.setSex(vo.getSex());
		memberPart.setBirthday(new Date());
		memberPart.setSignature("Hello World");
		memberPart.setItRole(CommonConstants.USER_IT_ROLE_OTHER);
		memberPartMapper.insertSelective(memberPart);
	}

	/**
	 * 校验用户是否存在
	 *
	 * @param loginId
	 * @return
	 */
	public ServiceResult<Boolean> checkUserExist(String loginId) {
		ServiceResult<Boolean> result = new ServiceResult<>();
		MemberInfo memberInfo = memberInfoMapper.loadUserByUsername(loginId);
		if (memberInfo != null) {
			result.setError(ResultCode.REQUEST_ERROR_EXIST_DATA, "用户已存在!");
			return result;
		}
		result.setResultData(true);
		return result;
	}
}
